module Main where

import Q.IR.Common
import Q.IR.Core
import Q.IR.Interpret

--------------------------------------------------------------------------------

{-

fac n =
  def loop (i, acc) =
    if (i < 1)
      return acc
    else
      loop (i - 1, acc * i)
  fac (n, 1)

-}

fac :: Expr -> Prog
fac n =
  PDefn [ (Id "loop",
            LabelDef (Id "arg") LInt $
            PCases (i `lt` EInt 1)
              [ (1, PJump Return acc)
              , (0, PJump (Label $ Id "loop") $
                    (ECons (i `sub` EInt 1) (acc `mul` i)))
              ]
          )
        ] $
  PJump (Label $ Id "loop") (ECons n (EInt 1))
  where
    i   = ERef (Id "arg") [P0]
    acc = ERef (Id "arg") [P1]

    lt  = EOp2 Op2LT
    mul = EOp2 Op2Mul
    sub = EOp2 Op2Sub

main :: IO ()
main = print =<< interpret (fac $ EInt 5)
